package cn.edu.sdjzu.knoverse.utils.login;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.edu.sdjzu.knoverse.utils.exception.CustomException;
import cn.edu.sdjzu.knoverse.model.dto.system.user.LoginDto;
import cn.edu.sdjzu.knoverse.model.entity.system.User;
import cn.edu.sdjzu.knoverse.model.vo.result.ResultCodeEnum;
import cn.edu.sdjzu.knoverse.mapper.UserMapper;
import cn.edu.sdjzu.knoverse.utils.PasswordEncoder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 使用用户名登录
 */
public class DefaultLoginStrategy implements LoginStrategy {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    public DefaultLoginStrategy(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 登录鉴定方法
     * 默认登录方式，使用用户名查询用户
     *
     * @param loginDto 登录参数
     * @return 鉴定身份验证
     */
    @Override
    public User authenticate(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        
        // 查询用户相关内容
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null) {
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        
        int readMeDay = loginDto.getReadMeDay();
        // 登录，并设置记住我的时间
        StpUtil.login(user.getId(), new SaLoginModel().setTimeout((long) readMeDay * 60 * 60 * 24));
        return user;
    }
}